<template>
  <div class="app-container">
    <div class="filter-container">
      <!-- <el-input v-model="listQuery.title" placeholder="昵称" style="width: 200px;" class="filter-item"
                @keyup.enter.native="handleFilter" />
            <el-button v-waves class="filter-item m-l-2" type="primary" icon="el-icon-search" @click="handleFilter">
                搜索
            </el-button> -->
      <el-button
        class="filter-item m-l-2"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="排序" type="index" width="80" />
      <el-table-column label="登录账号" align="center" min-width="150px">
        <template slot-scope="{row}">
          <span class="link-type">{{ row.username }}</span>
        </template>
      </el-table-column>
      <el-table-column label="昵称" align="center" min-width="150px">
        <template slot-scope="{row}">
          <span class="link-type">{{ row.nickname }}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色" align="center" min-width="150px">
        <template slot-scope="{row}">
          <el-tag type="success" effect="dark">{{ row.role.title }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="最近登录IP" align="center" min-width="150px">
        <template slot-scope="{row}">
          <span>{{ row.loginip }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最近登录时间" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.logintime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="添加时间" min-width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.create_time | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最近修改" min-width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.update_time | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="200px" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button
            v-if="row.status != 'deleted'"
            size="mini"
            type="danger"
            @click="handleDelete(row.id, $index)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-if="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="昵称账号" prop="nickname">
          <el-input v-model="temp.nickname" />
        </el-form-item>
        <el-form-item label="角色" prop="role_id">
          <el-select v-model="temp.role_id" class="filter-item" placeholder="角色选择" style="width: 100%;">
            <el-option
              v-for="item in rolelist"
              :key="item.key"
              :label="item.title"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="账号" prop="username">
          <el-input v-model="temp.username" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="temp.password" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getRole } from '@/api/role'
import { getAdmin, addAdmin, updateAdmin, deleteAdmin } from '@/api/admin'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'ComplexTable',
  components: { Pagination },
  directives: { waves },

  data() {
    return {
      rolelist: [],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        importance: undefined,
        title: undefined,
        type: undefined,
        sort: '+id'
      },

      temp: {
        role_id: 1,
        username: '',
        nickname: '',
        password: '123456'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        username: [{ required: true, message: 'username is required', trigger: 'blur' }],
        nickname: [{ required: true, message: 'nickname is required', trigger: 'blur' }],
        password: [{ required: true, message: 'password is required', trigger: 'blur' }],
        role_id: [{ required: true, message: 'role_id is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getRoleList()
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      getAdmin(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.count
        this.listLoading = false
      }).catch(err=>{
        console.log(err)
      })
    },
    getRoleList() {
      this.listLoading = true
      getRole({ limit: 100 }).then(response => {
        this.rolelist = response.data
        this.listLoading = false
      }).catch(err=>{
        console.log(err)
      })
    },
    // 搜索触发
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    // 添加弹窗的数据
    resetTemp() {
      this.temp = {
        role_id: null,
        username: '',
        nickname: '',
        password: ''
      }
    },
    // 添加弹窗
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 添加数据
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addAdmin(this.temp).then(response => {
            this.getList()
              //   this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: 'Created Successfully',
                type: 'success',
                duration: 2000
              })
          }).catch(err=>{
            console.log(err)
          })
        }
      })
    },
    // 编辑弹窗
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.fileList = [{ url: row.image }]
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateAdmin(tempData).then(response => {
            const index = this.list.findIndex(v => v.id === this.temp.id)
            this.getList()
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: 'Created Successfully',
                type: 'success',
                duration: 2000
              })
          }).catch(err=>{
            console.log(err)
          })
        }
      })
    },
    // 删除
    handleDelete(row, index) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteAdmin({ delete_ids: row }).then(response => {
          this.$notify({
              title: 'Success',
              message: 'Delete Successfully',
              type: 'success',
              duration: 2000
            })
            this.list.splice(index, 1)
        }).catch(err=>{
            console.log(err)
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }

  }
}
</script>
